import api from "../../utils/api"
import Utils from "../../utils/utils"
import animationHelper from '../..//utils/animation';

// pages/order/order.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    previewInfo: {} as PreviewOrderResult,//预览订单的信息
    orderContents: [] as OrderContentModel[],//商品内容信息
    remark: "" as string,//备注
    coupon: {} as CouponModel,//选择的order优惠券信息
    eventCode: "" as string,//活动码
    showCoupon: false as boolean,//是否展示优惠卷弹窗
    couponList: [] as CouponModel[],//order or commodity优惠券列表
    typeMap: {
      "BREAK": "折扣券",
      "MINUS": "满减券",
      "EXCHANGE": "兑换券"
    },//类型映射表
    type: "" as string,//order-打开的优惠券弹窗为订单优惠券,commodity-商品优惠券列表
    commodityID: 0 as number,//当前优惠券弹窗打开的物品ID
    fromCart: false as boolean,//是否来自购物车
    animation: null as WechatMiniprogram.Animation | null,
    animationData: {} as any,
  },
  // 修改地址
  changeAddress(): void {
    wx.navigateTo({
      url: '/pages/address/address?type=order'
    })
  },
  // 备注输入
  handleNotes(e: any): void {
    this.setData({
      remark: e.detail.value
    })
  },
  // 创建订单
  createOrder(): void {
    console.log("创建订单")
    const { previewInfo, coupon, eventCode, remark, orderContents, fromCart } = this.data
    const orderCommodities: Array<OrderCommodity> = orderContents.map(item => {
      return {
        commodityId: item.commodityId,
        count: item.count,
        couponId: item.couponId,
        cartContentId: item.cartContentId
      }
    })
    const params = {
      fromCart,
      addressId: previewInfo.address!.id,
      orderCommodities,
      couponId: coupon.id,
      eventCode,
      remark,
      channel: getApp().globalData.channel
    } as CreateOrderParam;
    console.log(coupon);
    api.order.createOrder(params).then(res => {
      if (res.data.code == "000" && res.data.data) {
        let payRequired = res.data.data.payRequired;
        let redirectUrl = "/pages/orderdetail/orderdetail?id=" + res.data.data.id;
        if (payRequired) {
          redirectUrl = redirectUrl + '&pay=1'
        }
        // 去支付
        wx.redirectTo({
          url: redirectUrl
        })
      } else {
        wx.showToast({
          title: res.data.message as string,
          icon: "error"
        })
      }
    })
  },
  // 数量减一
  subNum(e: any): void {
    const id = e.currentTarget.dataset.id;
    const orderContents = this.data.orderContents.map(item => {
      if (item.count && item.commodityId === id) {
        if (item.count != 1) {
          item.count--
        } else {
          wx.showToast({
            title: "数量不能为0",
            icon: "error"
          })
        }
      }
      return item;
    });
    this.setData({ orderContents });
  },
  // 数量加一
  addNum(e: any): void {
    const id = e.currentTarget.dataset.id;
    const orderContents = this.data.orderContents.map(item => {
      if (item.count && item.commodityId === id) {
        item.count++
      }
      return item;
    });
    this.setData({ orderContents });
  },
  // 选择商品优惠券
  chooseCommodityCoupon(e: any): void {
    // 当前商品索引
    const commodityIndex = e.currentTarget.dataset.index
    const commodityID = e.currentTarget.dataset.id
    const { previewInfo, orderContents, eventCode } = this.data
    console.log(this.data.orderContents);
    const params: GetUsableCouponListParam = {
      orderCoupon: false,
      addressId: previewInfo.address!.id,
      orderCommodities: orderContents,
      couponId: orderContents[commodityIndex].couponId,
      eventCode,
      commodityIndex
    }
    this.setData({
      commodityID
    })
    this.getUsableCouponList(params, "commodity")
  },
  // 选择订单优惠券
  chooseOrderCoupon(): void {
    const { previewInfo, orderContents, eventCode } = this.data
    const params: GetUsableCouponListParam = {
      orderCoupon: true,
      addressId: previewInfo.address!.id,
      orderCommodities: orderContents,
      eventCode,
    }
    this.getUsableCouponList(params, "order")
  },
  // 确认优惠券
  confirmCoupon(e: any): void {
    console.log(e.currentTarget.dataset.item)
    const { type, orderContents, commodityID } = this.data
    if (type == "order") {
      // 选择订单优惠券
      this.setData({
        coupon: e.currentTarget.dataset.item
      })
      this.previewOrder();
    } else {
      orderContents.forEach(item => {
        if (item.commodityId == commodityID) {
          item.couponId = e.currentTarget.dataset.item.id
        }
      })
      this.setData({
        orderContents
      })
      this.previewOrder();
    }
  },
  // 获取可用优惠券
  async getUsableCouponList(params: GetUsableCouponListParam, type: string): Promise<void> {
    const res = await api.order.getUsableCouponList(params)
    if (res.data.code == "000") {
      const list = res.data.data
      if (list) {
        list.forEach(item => {
          item.expireTime = Utils.timestampToDateTime(item.expireTime as number)
        })
        this.setData({
          couponList: list,
          type
        })
        const animation = animationHelper.createAnimation(500, 'ease');
        this.setData({ animation: animation });
        animationHelper.showAnimation(animation, 478, this.setData.bind(this), "showCoupon");
      }
    } else {
      wx.showToast({
        title: res.data.message as string,
        icon: "error"
      })
    }
  },
  // 关闭弹窗
  closeDialog() {
    const animation = this.data.animation;
    animationHelper.closeAnimation(animation, 478, this.setData.bind(this), "showCoupon");
  },
  // 切换地址,选择优惠券都掉预览订单
  previewOrder(): void {
    const { eventCode, previewInfo, orderContents, coupon } = this.data
    const orderCommodities = orderContents.map(item => {
      return {
        commodityId: item.commodityId,
        cartContentId: item.cartContentId,
        count: item.count,
        couponId: item.couponId
      }
    })
    const params = {
      addressId: previewInfo.address!.id,
      autoSelectCoupon: false,
      orderCommodities,
      couponId: coupon.id,
      eventCode,
      fromCart: false
    } as PreviewOrderParam
    api.order.previewOrder(params).then(res => {
      // 关闭弹窗
      this.closeDialog()
      if (res.data.code == "000") {
        if (res.data.data) {
          this.format(res.data.data)
        }
      } else {
        wx.showToast({
          title: res.data.message as string,
          icon: "error"
        })
      }
    })
  },
  format(previewInfo: PreviewOrderResult): void {
    previewInfo.commodityAmount = Utils.priceToYuan(previewInfo.commodityAmount as number)
    previewInfo.totalAmount = Utils.priceToYuan(previewInfo.totalAmount as number)
    previewInfo.couponDiscount = Utils.priceToYuan(previewInfo.couponDiscount as number)
    previewInfo.shippingCost = Utils.priceToYuan(previewInfo.shippingCost as number)
    if (previewInfo.orderContents) {
      previewInfo.orderContents.forEach((item: OrderContentModel) => {
        item.price = Utils.priceToYuan(item.price as number)
        item.couponAmount = Utils.priceToYuan(item.couponAmount as number)
      })
    }
    let coupon = {};
    if (previewInfo.couponId) {
      coupon = {
        id: previewInfo.couponId,
        name: previewInfo.couponName,
      }
    }
    this.setData({
      previewInfo,
      orderContents: previewInfo.orderContents,
      coupon
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options: any) {
    try {
      const previewInfo = JSON.parse(decodeURIComponent(options.data))
      const fromCart = Boolean(Number(options.fromCart))
      const eventCode = options.eventCode
      this.setData({
        fromCart,
        eventCode
      })
      this.format(previewInfo)
    } catch (error) {
      console.error('Failed to stringify object:', error);
    }
  },
})